和为S的连续正整数序列

和为S的连续正整数序列

题目描述

  • 输出所有和为S的连续正数序列。序列内按照从小至大的顺序,序列间按照开始数字从小到大的顺序

  • 由求和公式得 (i+1)(2a+i)/2=sum;我们只需要找出对应的a和i

  • 若只有两个数,则最大的为折半的数,比如s=89,两个数字组成的序列为 44,45

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function FindContinuousSequence(sum)
{
// write code here
//(i+1)*(2*a+i)=2*sum;
let i=1,a=0;
const res=[];
let half=sum>>1;
while(half--){
a++;
i=1;
while((i+1)*(2*a+i)<2*sum){
i++;
}
if((i+1)*(2*a+i)==2*sum){
const tmp=[]
tmp.push(i);
tmp.push(a);
res.push(tmp);
}
}
const reslist=[]
let temp=[]
for(var j=0;j< res.length;j++){
var a1=res[j][1]
temp=[]
for(var k=0;k<=res[j][0];k++){
temp.push(a1);
a1++;
}
reslist.push(temp)
}
return reslist
}